let express = require("express");
let app = express();
const mongoose = require("mongoose");
app.listen(6789, function () {
    console.log("服务器监听6789端口");
// 服务器开启再链接数据库
    mongoose.connect("mongodb://127.0.0.1:27017/cartdb", {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
        useCreateIndex: true
    });
});
//监听
mongoose.connection.on("open", function () {
    console.log("数据库链接成功");
    const schema = new mongoose.Schema({
        proName: String,
        proPrice: String,
        proInfo: String,
        category: String,
    }, {collection: "product"});
    let myModel = mongoose.model("product", schema)
    const schemaadd = new mongoose.Schema({
        proName: String,
        proPrice: String,
        num:Number,
        id:String,
    }, {collection: "add"});
    let myModeladd = mongoose.model("add", schemaadd)
    // myModel.create({proName: "秋裤", proPrice: "998", proInfo: "没用秋裤", category: "保暖"})
//   查询全部
    app.get("/allProduct", function (req, res) {
        myModel.find(function (error, result) {
            if (!error) {
                res.json(result);
            } else {
                res.end();
            }
        })
    });
//    分类
    app.get("/classify", function (req, res) {
// console.log(req.query.cate);
        let cate = req.query.cate
        myModel.find({category: cate}, function (error, result) {
            if (!error) {
                res.json(result);
            }else {
                res.end();
            }
        })
    })
//    添加购物车
    app.get("/add",function (req,res) {
        let name=req.query.proName;
        let price=req.query.proPrice;
        let id=req.query.id;
        let num=1;
        myModeladd.find({id:id},function (error,result) {
            if (result.length==0){
                myModeladd.create({proName:name,proPrice:price,num:num,id:id},function (error,result) {
                    res.json(result);
                })
                console.log("添加商品")
            }else{
              num=result[0].num+1;
                console.log(num)
                myModeladd.updateOne({id:id},{num:num},function (error,result) {
                    // console.log(result[0].num)
                            res.json(result);
                        })
                // console.log( "数量想加了" ,result)
            }
        })

    });
//    查询
    app.get('/look',function (req,res) {
myModeladd.find(function (error,result) {
res.json(result);
})
    });
    app.get('/show',function (req,res) {
        myModeladd.find(function (error,result) {
            res.json(result);
        })
    })



//    监听结尾
})
